//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.sie.peripheral;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import com.bankcomm.peripheral.BankCardInfoBean;
import com.bankcomm.peripheral.EmvOptions;
import com.bankcomm.peripheral.IdentityInfoBean;
import com.bankcomm.peripheral.PeripheralCallback;
import com.bankcomm.peripheral.PeripheralInterface;
import com.printer.sdk.PrinterInstance;
import com.sie.framework.appinterface.Api;
import com.sie.framework.bean.BankCardBean;
import com.sie.framework.bean.IdentityBean;
import com.sie.framework.bean.TradeLogBean;
import com.sie.framework.channel.ChannelInstance;
import com.sie.framework.constconfig.ErrorDefine;
import com.sie.framework.device.SiecomDevice;
import com.sie.framework.device.SiecomTask.TaskCallback;
import com.sie.framework.listen.DeviceConStatusListen;
import com.sie.framework.plugin.printer.BluetoothOperation;
import com.sie.tools.ByteTool;
import com.sie.tools.LogUtil;
import com.sie.tools.StringUtil;
import com.sie.zhq.module.DeviceCallback;
import com.sie.zhq.module.DeviceInterface;
import com.sie.zhq.tool.ToastUtils;
//import com.techshino.fp.client.TcFingerClient;
//import com.techshino.fp.util.FpConfig;
//import com.techshino.fp.util.OnUsbConnectListener;
//import com.techshino.fp.util.USBUtil;

import android.util.Base64;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.zip.CRC32;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class SiecomPeripheral implements PeripheralInterface {
    public static final int BTCONNECT = 2;
    public static final int LINECONNECT = 1;
    public static int CONNECTIONMODE = -1;
    public static final String org = "ZG";
    private static SoundPool soundPool;
    public static int speakerId;
    HashMap<Integer, Integer> musicId = new HashMap();
    public static final int MSR_TYPE = 1;
    public static final int IC_TYPE = 2;
    public static final int PICC_TYPE = 3;
    public static final int AUTO_TYPE = 4;
    public static final String A108 = "P3520-";
    public long now;
    public static boolean printerFlag = false;
    private BluetoothOperation mPrinter;
    public static Context context;
    private MediaPlayer mediaPlayer;
    volatile boolean overFlag = true;
    private boolean IDCard = false;
//    USBUtil mUsbUtil;
//    TcFingerClient mClient;
    private byte[] mTemplate;
    private Context mContext;
    private String TAG = this.getClass().getSimpleName();
    private int index = 0;
    
    private static boolean powerFlag = false;

    final static String arpc = "910A2501EEC5A3FDBF563030";//91开头，脚本是72开头
    final static String script = "7251860F04DA9F790A000000000000A4B17D6D860F04DA9F770A0000001000008C09E6BF862D04DC010C2870229F61123433313232313139383830373136313231589F6201105F2006C5CBB0D8D3EEA168BB5A";

    public static int TimeOut = 45000;
    private boolean fingerprintConnection = false;
    private static final String BASE_PATH = Environment
            .getExternalStorageDirectory().getPath();
    private static final String TEMPLATE_PATH = BASE_PATH + "/Tc_Template.bin";
    
    public boolean portIsOpen = false;
    public static String PORT = "/dev/ttyUSB1";

    
    
    public SiecomPeripheral() {
    }

    public void setContext(Context context) {
    	mContext = context;
        ChannelInstance.setContext(context);
//        initEPP(); //打开串口
    }

    public int connectDevice(int connectMode) {
    	CONNECTIONMODE = connectMode;
        if (connectMode == 2) {
            return ChannelInstance.initDevice(0, "P3520-");
        } else {
//        	policemen();
        	powerOn();
        	return 0;
//            return connectMode == 1 ? ChannelInstance.initDevice(1, "P3520-") : -1;
        }
    }

    
//    private void policemen(){
////    	//Log.e("GJ", "有数据吗"+mContext);
//        mUsbUtil = USBUtil.getInstance(mContext);
//        // 设置设备使用协议
//        mUsbUtil.setProtocol(USBUtil.Protocol.SIMPLE);
//        // 设置特征类型
//        FpConfig.setFeatureType(FpConfig.FEATURE_TYPE_GA);
//        // 设置出图规格
//        FpConfig.setImageType(FpConfig.IMAGE_BIG);
//        // 注册广播
//        mUsbUtil.registerMonitor();
//
//        FpConfig.setQualityScore(40);
//
//
//        mUsbUtil.setConnectListener(new OnUsbConnectListener() {
//
//            @Override
//            public void onConnected(TcFingerClient client) {
////                ToastUtils.showToast(mContext, "设备连接成功");
////                displayMessage("设备连接成功");
//                mClient = client;
//                fingerprintConnection = true;
//            }
//
//            @Override
//            public void onConnectFailed(int code, String msg) {
////                ToastUtils.showToast(mContext, msg);
//            	//Log.e("GJ", "设备连接失败");
//            	fingerprintConnection = false;
//            }
//
//            @Override
//            public void onDisconnected() {
//            	//Log.e("GJ", "onDisconnected");
//                super.onDisconnected();
////                mProgressDialog.dismiss();
//            }
//
//            @Override
//            public void onAttach(UsbDevice usbDevice) {
//                // TODO Auto-generated method stub
//            	//Log.e("GJ", "onAttach");
//            	IDCard = true;
//                super.onAttach(usbDevice);
//                // connBtnClick();
//            }
//
//            @Override
//            public void onDettach(UsbDevice usbDevice) {
//                // TODO Auto-generated method stub
//            	fingerprintConnection = false;
//            	IDCard = false;
//            	//Log.e("GJ", "onDettach");
//                super.onDettach(usbDevice);
//            }
//        });
//        mTemplate = getTemplateFromDisk();
//        connBtnClick();
//    }
    
    public void disconnBtnClick() {
//      mProgressDialog.show();
//      mUsbUtil.asynDisconnectDevice();
  }
  
//    protected void connBtnClick() {
//        mUsbUtil.connectDevice();
//    }
    
    private byte[] getTemplateFromDisk() {
        File file = new File(TEMPLATE_PATH);
        if (!file.exists()) {
            return null;
        }

        FileInputStream in = null;

        try {
            in = new FileInputStream(file);
            int length = in.available();

            byte[] buffer = new byte[length];
            in.read(buffer);

            return buffer;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            // 关闭创建的流对象
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    public int getPrinterStatus(PeripheralCallback callback) {
        Bundle bundle = new Bundle();
        if (PrinterInstance.mPrinter != null) {
            int code = PrinterInstance.mPrinter.getCurrentStatus();
            LogUtil.mLog("sdk getCurrentStatus:" + code);
            switch(code) {
            case -2:
                bundle.putString("code", "1");
                bundle.putString("message", "打印机断开连接");
                if (callback != null) {
                    callback.onFail(bundle);
                }

                return 1;
            case -1:
                bundle.putString("code", "0");
                bundle.putString("message", "打印机已连接");
                if (callback != null) {
                    callback.onSuccess(bundle);
                }

                return 0;
            case 0:
                bundle.putString("code", "0");
                bundle.putString("message", "打印机已连接");
                if (callback != null) {
                    callback.onSuccess(bundle);
                }

                return 0;
            default:
                bundle.putString("code", "1");
                bundle.putString("message", "打印机断开连接");
                if (callback != null) {
                    callback.onFail(bundle);
                }

                return 1;
            }
        } else {
            bundle.putString("code", "1");
            bundle.putString("message", "打印机断开连接");
            if (callback != null) {
                callback.onFail(bundle);
            }

            return 1;
        }
    }

    private static int indexKeyFix(int index) {
        if (index == 0) {
            return 9;
        } else {
            return index > 0 && index < 10 ? index - 1 : 0;
        }
    }

    public boolean connectPrinter(PeripheralCallback callback) {
        String BluetoothPrinterDevice = "T9";
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            Iterator iterator = pairedDevices.iterator();

            while(iterator.hasNext()) {
                BluetoothDevice device = (BluetoothDevice)iterator.next();
                if (device.getName().startsWith(BluetoothPrinterDevice)) {
                    mBluetoothAdapter.enable();
                    this.mPrinter = new BluetoothOperation(callback);
                    this.mPrinter.open(device);
                    return true;
                }
            }
        }

        return false;
    }

    public void disConnectDevice() {
        ChannelInstance.destroy();
    }

    public int listenDeviceStatus(final PeripheralCallback callback) {
        SiecomDevice.deviceConnStatusChange(new DeviceConStatusListen() {
            public void onDisconnect() {
                Log.e("conn", "onDisconnect");
                SiecomDevice.cancelLastTask(false);
                if (callback != null) {

                    SiecomDevice.jiaohang_CancelTask(true);
                    Bundle bundle = new Bundle();
                    bundle.putString("code", "-0000");
                    bundle.putString("data", "设备异常");
                    bundle.putString("message", "设备连接断开");
                    callback.onFail(bundle);
                }

            }

            public void connected() {
                Log.e("conn", "connected");
                if (callback != null) {
                    Bundle bundle = new Bundle();
                    bundle.putString("data", "设备正常");
                    callback.onSuccess(bundle);
                }

            }

            public void connecting() {
                Log.e("conn", "connecting");
            }
        });
//        mHandlers.postDelayed(mRunnable, 1000);
        return 0;
    }
//    Handler mHandlers = new Handler();
//    Runnable mRunnable = new Runnable() {
//		
//		@Override
//		public void run() {
//			// TODO 自动生成的方法存根
//			DeviceStatus();
//	        mHandlers.postDelayed(mRunnable, 1000);
//			
//		}
//	};
    
    private void DeviceStatus(){
    	BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //获取状态码
       int test =  mBluetoothAdapter.getState();
//       //Log.e("GJ", "状态码");
        //判断蓝牙状态
        switch (test){
            case BluetoothAdapter.STATE_CONNECTED:
//                //Log.e("GJ", "判断状态为连接中");
                break;
            case BluetoothAdapter.STATE_CONNECTING:
//            	//Log.e("GJ", "判断状态为连接");
                break;
            case BluetoothAdapter.STATE_DISCONNECTED:
//            	//Log.e("GJ", "判断状态为断开" );
                break;
            case BluetoothAdapter.STATE_DISCONNECTING:
//            	//Log.e("GJ", "判断状态为断中" );
                break;
            case BluetoothAdapter.STATE_OFF:
//            	//Log.e("GJ", "关闭" );
                break;
            case BluetoothAdapter.STATE_ON:
//            	//Log.e("GJ", "打开" );
                break;
            default:
                break;
        }
    }
    @SuppressLint({"SimpleDateFormat"})
    public void ReadBankCardInfo(int readMode, final PeripheralCallback callback, int timeOut) {
    	TimeOut = timeOut;
        int cardType = 0;
        if (readMode == 1) {
            cardType = 2;
        } else if (readMode == 2) {
            cardType = 0;
        } else if (readMode == 3) {
            cardType = 1;
        } else if (readMode == 4) {
            cardType = 3;
        }
        //Log.e("GJjiaohang", "开启读取银行卡中..."+"卡片信息"+readMode+"超时时间"+timeOut);
        if(CONNECTIONMODE == BTCONNECT){
            TaskCallback taskCallback = new TaskCallback() {
                public void onStart(Bundle bundle) {
                    SiecomPeripheral.this.now = System.currentTimeMillis();
                }

                public void onSucceed(Bundle bundle) {
                    BankCardBean bean = (BankCardBean)bundle.getParcelable("data");
                    long finish = System.currentTimeMillis();
                    Log.e("useTime:", finish - SiecomPeripheral.this.now + "ms");
                    BankCardInfoBean infobean = new BankCardInfoBean();

                    try {
                        if (bean.cardType == 0) {
                            infobean.readMode = 2;
                        } else if (bean.cardType == 1) {
                            infobean.readMode = 3;
                        } else if (bean.cardType == 2) {
                            infobean.readMode = 1;
                        }

                        if (bean.cardType != 0 && bean.cardType != 1) {
                            infobean.cardNo = bean.cardNo;
                            infobean.track1Data = bean.oneMagneticTrack;
                            infobean.track2Data = bean.twoMagneticTrack;
                            infobean.track3Data = bean.threeMagneticTrack;
                        } else {
                            Log.e("info:", bean.ICChipData);
                            String userName = StringUtil.tagParse("5F20", bean.ICChipData);
                            byte[] nameByte = ByteTool.hexStr2Bytes(userName);

                            try {
                                infobean.userName = (new String(nameByte, "gb2312")).trim();
                                Log.e("userName：", (new String(nameByte, "gb2312")).trim());
                            } catch (UnsupportedEncodingException var19) {
                                var19.printStackTrace();
                            }

                            infobean.cardNo = bean.cardNo;
                            String credentialType = StringUtil.tagParse("9F62", bean.ICChipData);
                            infobean.credentialType = credentialType;
                            Log.e("credentialType：", credentialType);
                            String documentNumber = StringUtil.tagParse("9F61", bean.ICChipData);
                            byte[] documentByte = ByteTool.hexStr2Bytes(documentNumber);
                            infobean.documentNumber = (new String(documentByte)).trim();
                            Log.e("documentNumber：", (new String(documentByte)).trim());
                            int len5A = StringUtil.getTagLen(0, "5A", bean.ICChipData);
                            String track2Data = StringUtil.tagParse(len5A * 2 + 2, "57", bean.ICChipData);
                            if(track2Data != null && !track2Data.trim().equals("")){
                            	track2Data = track2Data.replace("D", "=");
                                if (track2Data.indexOf("F") != -1) {
                                    track2Data = track2Data.substring(0, track2Data.indexOf("F"));
                                }

                                infobean.track2Data = track2Data;
                                Log.e("track2Data：", track2Data);
                            }
                            
                            String track1Data = StringUtil.tagParse("9F1F", bean.ICChipData);
                            infobean.track1Data = track1Data;
                            Log.e("track1Data：", track1Data);
                            String accountBalance = StringUtil.tagParse("9F79", bean.ICChipData);
                            infobean.accountBalance = accountBalance;
                            Log.e("accountBalance：", accountBalance);
                            String balanceCap = StringUtil.tagParse("9F77", bean.ICChipData);
                            infobean.balanceCap = balanceCap;
                            Log.e("balanceCap：", balanceCap);
                            String expDate = StringUtil.tagParse("5F24", bean.ICChipData);
                            //获取失效日期
                            if(expDate.equals("00000000") || TextUtils.isEmpty(expDate)){
                                expDate = getExpDataByTrack2(track2Data);
                            }
                            infobean.expDate = expDate;
                            Log.e("expDate：", expDate);
                            String serialNumber = StringUtil.tagParse("5F34", bean.ICChipData);
                            infobean.serialNumber = serialNumber;
                            Log.e("serialNumber：", serialNumber);
                            int pos = bean.ICChipData.indexOf("9F26");
                            if(pos != -1){
                                bundle.putString("55field", bean.ICChipData.substring(pos));
                            }else{
                            	bundle.putString("55field", "");
                            }
                        }

                        if (callback != null) {
                            bundle.putParcelable("data", infobean);
                            callback.onSuccess(bundle);
                        }
                    } catch (ArrayIndexOutOfBoundsException var20) {
                        var20.printStackTrace();
                        if (callback != null) {
                            bundle.putString("code", String.valueOf(var20.hashCode()));
                            bundle.putString("message", var20.getMessage());
                            callback.onFail(bundle);
                        }
                    }bundle.putString("message", bundle.getString("message"));

                    SiecomDevice.shutDownCard();
                }

                public void onError(Bundle bundle) {
                    if (callback != null) {
//                        DbgLogger.mLog(bundle.getString("code") + "--" + bundle.getString("message") + "--" + bundle.getInt("code"));
//                        bundle.putString("code", ""+-1005);

                        //Log.e("GJjiaohang", "读取银行卡失败错误是"+bundle.getString("message")+bundle.getString("code"));
                    	
                        callback.onFail(bundle);
                    }

//                    if (bundle.getString("code").equals("-1001") || bundle.getString("code").equals("-1002") || bundle.getString("code").equals("-1003")) {
////                        SiecomDevice.shutDownCard();
//                    }

                }
            };
            EmvOptions options = new EmvOptions();
            SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");
            String time = df.format(new Date());
            options.setTime(time);
            byte[] MerchCateCode = new byte[]{0, 1};
            options.setMerchCateCode(MerchCateCode);
            String MerchId = "123456789012345";
            options.setMerchId(MerchId.getBytes());
            options.setMerchName("EMV LIBRARY".getBytes());
            options.setTermId("12345678".getBytes());
            options.setTerminalType((byte)34);
            options.setSupportPSESel((byte)1);
            byte[] Capability = new byte[]{-32, 96, -56};
            options.setCapability(Capability);
            byte[] ExCapability = new byte[]{96, 0, -16, 32, 1};
            options.setExCapability(ExCapability);
            byte[] CountryCode = new byte[]{1, 86};
            options.setCountryCode(CountryCode);
            options.setTransCurrCode(CountryCode);
            options.setTransCurrExp((byte)2);
            options.setReferCurrCode(CountryCode);
            options.setCL_TransLimit(100000);
            options.setTransType((byte)0);
            options.setECTSI((byte)1);
            options.setEC_TermLimit(10000);
            options.setEC_bTermLimitCheck((byte)1);
            byte[] TermTransQuali = new byte[]{36, 0, 0, -128};
            options.setTermTransQuali(TermTransQuali);
            options.setCL_bStatusCheck((byte)0);
            options.setCL_CVMLimit(10000);
            options.setCL_FloorLimit(20000);
            options.setTransNo(1);
            String[] tags = new String[]{"5A", "57", "5F20", "9F62", "9F61", "9F1F", "9F79", "9F77", "5F24", "5F34", "9F26", "9F27", "9F10", "9F37", "9F36", "95", "9A", "9C", "9F02", "5F2A", "82", "9F1A", "9F03", "9F33", "9F34"};
            options.setTags(tags);
            SiecomDevice.ReadBankCard(cardType, options, taskCallback, timeOut);
            
        }else {
            DeviceInterface.autoCardInfo(new DeviceCallback() {
                @Override
                public void onStart() {
//                    infoText.setText("");
//                    spb.setVisibility(View.VISIBLE);
//                    spb.progressiveStart();
//                    Snackbar.make(rootView, getResources().getText(R.string.please_card), Snackbar.LENGTH_LONG)
//                            .setAction("Action", null).show();
                }

                @Override
                public void onError(Bundle bundle) {
                    if (callback != null) {
                        LogUtil.mLog(bundle.getString("code") + "--" + bundle.getString("message") + "--" + bundle.getInt("code"));
                        callback.onFail(bundle);
                    }

                    if (bundle == null || bundle.getString("code") == null || bundle.getString("code").equals("-1001") || bundle.getString("code").equals("-1002") || bundle.getString("code").equals("-1003")) {
//                        SiecomDevice.shutDownCard();
                    }

                }

                @Override
                public void onSuccess(Bundle bundle) {
//                    BankCardInfoBean bean = bundle.getParcelable("data");
//                    showCardInfo(bean);
                    // arpcBtn.setVisibility(View.VISIBLE);

//                    BankCardBean bean = (BankCardBean)bundle.getParcelable("data");
                    long finish = System.currentTimeMillis();
                    Log.e("useTime:", finish - SiecomPeripheral.this.now + "ms");
                    BankCardInfoBean infobean = (BankCardInfoBean)bundle.getParcelable("data");

                    try {
                        if (infobean.cardType == 0) {
                            infobean.readMode = 2;
                        } else if (infobean.cardType == 1) {
                            infobean.readMode = 3;
                        } else if (infobean.cardType == 2) {
                            infobean.readMode = 1;
                        }

                        if (infobean.cardType != 0 && infobean.cardType != 2) {
                            infobean.cardNo = infobean.cardNo;
                            infobean.track1Data = infobean.track1Data;
                            infobean.track2Data = infobean.track2Data;
                            infobean.track3Data = infobean.track3Data;
                        } else {
//                            Log.e("info:", infobean.ICChipData);
                            String userName = StringUtil.tagParse("5F20", infobean.ictag);
                            byte[] nameByte = ByteTool.hexStr2Bytes(userName);

                            try {
                                infobean.userName = (new String(nameByte, "gb2312")).trim();
                                Log.e("userName：", (new String(nameByte, "gb2312")).trim());
                            } catch (UnsupportedEncodingException var19) {
                                var19.printStackTrace();
                            }

//                            infobean.cardNo = bean.cardNo;
                            String credentialType = StringUtil.tagParse("9F62", infobean.ictag);
                            infobean.credentialType = credentialType;
                            Log.e("credentialType：", credentialType);
                            String documentNumber = StringUtil.tagParse("9F61", infobean.ictag);
                            byte[] documentByte = ByteTool.hexStr2Bytes(documentNumber);
                            infobean.documentNumber = (new String(documentByte)).trim();
                            Log.e("documentNumber：", (new String(documentByte)).trim());
                            int len5A = StringUtil.getTagLen(0, "5A", infobean.ictag);
                            String track2Data = StringUtil.tagParse(len5A * 2 + 2, "57", infobean.ictag);
                            if(track2Data != null && !track2Data.trim().equals("")){
                            	track2Data = track2Data.replace("D", "=");
                                if (track2Data.indexOf("F") != -1) {
                                    track2Data = track2Data.substring(0, track2Data.indexOf("F"));
                                }

                                infobean.track2Data = track2Data;
                                Log.e("track2Data：", track2Data);
                            }
                            
                            String track1Data = StringUtil.tagParse("9F1F", infobean.ictag);
                            infobean.track1Data = track1Data;
                            Log.e("track1Data：", track1Data);
                            String accountBalance = StringUtil.tagParse("9F79", infobean.ictag);
                            infobean.accountBalance = accountBalance;
                            Log.e("accountBalance：", accountBalance);
                            String balanceCap = StringUtil.tagParse("9F77", infobean.ictag);
                            infobean.balanceCap = balanceCap;
                            Log.e("balanceCap：", balanceCap);
                            String expDate = StringUtil.tagParse("5F24", infobean.ictag);
                            //获取失效日期
                            if(expDate.equals("00000000") || TextUtils.isEmpty(expDate)){
                                expDate = getExpDataByTrack2(track2Data);
                            }
                            infobean.expDate = expDate;
                            Log.e("expDate：", expDate);
                            String serialNumber = StringUtil.tagParse("5F34", infobean.ictag);
                            infobean.serialNumber = serialNumber;
                            Log.e("serialNumber：", serialNumber);
                            int pos = infobean.ictag.indexOf("9F26");
                            if(pos != -1){
                                bundle.putString("55field", infobean.ictag.substring(pos));
                            }else{
                            	bundle.putString("55field", "");
                            }
                        }

                        if (callback != null) {
                            bundle.putParcelable("data", infobean);
                            callback.onSuccess(bundle);
                        }
                    } catch (ArrayIndexOutOfBoundsException var20) {
                        var20.printStackTrace();
                        if (callback != null) {
                            bundle.putString("code", String.valueOf(var20.hashCode()));
                            bundle.putString("message", var20.getMessage());
                            callback.onFail(bundle);
                        }
                    }

//                    SiecomDevice.shutDownCard();
                
                }

                @Override
                public void onCompleted(Bundle bundle) {
//                    spb.progressiveStop();

                }
            }, 15000, true);
        }
       
    }
    public String getExpDataByTrack2(String track2){
        if(TextUtils.isEmpty(track2)){
            return "000000";
        }
        int index = track2.indexOf("=");
        if(index < 0){
            index = track2.indexOf("D");
        }

        if(index < 12){
            return "000000";
        }

        String exp = track2.substring(index + 1,index + 5);
//        Log.e(TAG,"expDate == "+ exp);
        String year = track2.substring(index + 1  ,index + 3);
//        Log.e(TAG,"year ==  "+ year);
        String month = track2.substring(index + 3,index + 5);
//        Log.e(TAG,"month ==  "+ month);
        String date = "31";
        if(month.equals("01") || month.equals("03") ||month.equals("05") ||
                month.equals("07") ||month.equals("08") || month.equals("10") ||month.equals("12")){
            date = "31";
        }else if(month.equals("04") || month.equals("06") ||month.equals("09") || month.equals("11") ){
            date = "30";
        }else if (month.equals("02")){
            int y = Integer.parseInt("20" + year);
            if(y%4 == 0){
                date = "29";
            }else {
                date = "28";
            }
        }

        return exp + date;
    }
    
    public void ReadIDCardInfo(final String type, final PeripheralCallback callback, int timeOut) {
    	TimeOut = timeOut;
    	if(CONNECTIONMODE == BTCONNECT){
    		TaskCallback taskCallback = new TaskCallback() {
                public void onStart(Bundle bundle) {
                }

                public void onSucceed(Bundle bundle) {
                    LogUtil.e(TAG, "ReadIDCardInfo onSucceed");
                    IdentityBean bean = (IdentityBean)bundle.getParcelable("data");
                    IdentityInfoBean infobean = new IdentityInfoBean();
                    
                    //居民身份证
                    
                    infobean.fullName = bean.fullName;
                    infobean.address = bean.idAddr;
                    infobean.effectiveDate = bean.beginDate;
                    infobean.expDate = bean.endDate;
                    infobean.photo = bean.icon;
                    infobean.fingerData = bean.fingerByte;
                    infobean.gender = bean.sex;
                    infobean.birthday = bean.birthday;
                    infobean.organization = bean.idOrg;
                    infobean.identityCardNumber = bean.idNo;
                    infobean.nation = bean.nation;
                    
                    
                    //外国人居住证
                    
                    infobean.fFullName = bean.fullName;
                    infobean.fGender = bean.sex;
                    infobean.fCardTag = bean.cardType;
                    infobean.fBirthday = bean.birthday;
                    infobean.fEngName = bean.enName;
                    infobean.fCardVersion = bean.cardVer;
                    infobean.fIdentityCardNumber = bean.idNo;
                    infobean.fEffectiveDate = bean.beginDate;
                    infobean.fExpDate = bean.endDate;
                    infobean.fOrganization = bean.idOrg;
                    infobean.fNationCode = bean.countryCode;
                    infobean.fNation = bean.nation;
                    infobean.fAddition = "";
                    infobean.fingerData = new byte[0];
                    
                    //港澳居住证
                    infobean.photoLocal = Environment.getExternalStorageDirectory() + "/"+"wltlib"+"/zp.bmp";
                    infobean.gAddress = bean.idAddr;
                    infobean.gFullName = bean.fullName;
                    infobean.gGender = bean.sex;
                    infobean.gCardTag = bean.cardType;
                    infobean.gBirthday = bean.birthday;
                    infobean.gIdentityCardNumber = bean.idNo;
                    infobean.gEffectiveDate = bean.beginDate;
                    infobean.gExpDate = bean.endDate;
                    infobean.gOrganization = bean.idOrg;
                    infobean.gPassNumber = bean.passportNo;
                    infobean.gSignCount = bean.issuingNo;
                    infobean.gReserveA = bean.reserveA;
                    infobean.gReserveB = bean.reserveB;
                    infobean.gReserveC = bean.reserveC;
                    
                    String tmpType = type;
                    if (type == null) {
                        tmpType = "0";
                    }

                    if(bean.cardType == null){
                        Bundle bundleErr = new Bundle();
                        bundleErr.putString("code", "-1101");
                        bundleErr.putString("message", "读取身份证失败");
                        callback.onFail(bundleErr);
                        return;
                    }
                    if (!bean.cardType.equals(tmpType)) {
                        Bundle bundle2 = new Bundle();
                        if ("0".equals(tmpType)) {
                            bundle2.putString("code", "-1105");
                            bundle2.putString("message", "实物证件与选择的证件类型不匹配，请放置二代居民身份证");
                        } else if ("1".equals(tmpType)) {
                            bundle2.putString("code", "-1106");
                            bundle2.putString("message", "实物证件与选择的证件类型不匹配，请放置外国人永久居留证");
                        }else if ("2".equals(tmpType)) {
                            bundle2.putString("code", "-1107");
                            bundle2.putString("message", "实物证件与选择的证件类型不匹配，请放置港澳台身份证");
                        }

                        if (callback != null) {
                            callback.onFail(bundle2);
                        }

                    } else {
                        if (callback != null) {
                            bundle.putParcelable("data", infobean);
                            callback.onSuccess(bundle);
                        }

                    }
                }

                public void onError(Bundle bundle) {
                    if (callback != null) {
                        String errCode = bundle.getString("code");
                        String tmpType = type;
                        if (null != errCode && errCode.equals("-1104") && "1".equals(tmpType)) {
                            bundle.putString("code", "-1107");
                            bundle.putString("message", "永居证读取超时");
                        }

                    	//Log.e("GJ", "读取身份证:"+ bundle.getString("message"));
                        callback.onFail(bundle);
                    }

                }
            };
            SiecomDevice.ReadIdentity(true, taskCallback, timeOut);
    	}else{
//    		if(IDCard == false){
//    			ToastUtils.showToast(mContext, "请先打开身份证按钮");
//    			return;
//    		}
//    		DeviceInterface.readIdentity(new DeviceCallback() {
//                @Override
//                public void onStart() {
//                    
//                }
//
//                @Override
//                public void onError(Bundle bundle) {
//                	if (callback != null) {
//                        String errCode = bundle.getString("code");
//                        String tmpType = type;
//                        if (errCode.equals("-1104") && "1".equals(tmpType)) {
//                            bundle.putString("code", "-1107");
//                            bundle.putString("message", "永居证读取超时");
//                        }
//
//                        callback.onFail(bundle);
//                    }
//                }
//
//                @Override
//                public void onSuccess(Bundle bundle) {
//
//                	Log.e("ReadIDCardInfo", "ReadIDCardInfo");
//                	IdentityInfo317Bean bean = (IdentityInfo317Bean)bundle.getParcelable("data");
//                    IdentityInfoBean infobean = new IdentityInfoBean();
//                    
//                    //居民身份证
//                    
//                    infobean.fullName = bean.fullName;
//                    infobean.address = bean.idAddr;
//                    infobean.effectiveDate = bean.beginDate;
//                    infobean.expDate = bean.endDate;
//                    infobean.photo = bean.icon;
//                    infobean.fingerData = bean.fingerByte;
//                    infobean.gender = bean.sex;
//                    infobean.birthday = bean.birthday;
//                    infobean.organization = bean.idOrg;
//                    infobean.identityCardNumber = bean.idNo;
//                    infobean.nation = bean.nation;
//                    
//                    
//                    //外国人居住证
//                    
//                    infobean.fFullName = bean.fullName;
//                    infobean.fGender = bean.sex;
//                    infobean.fCardTag = bean.cardType;
//                    infobean.fBirthday = bean.birthday;
//                    infobean.fEngName = bean.enName;
//                    infobean.fCardVersion = bean.cardVer;
//                    infobean.fIdentityCardNumber = bean.idNo;
//                    infobean.fEffectiveDate = bean.beginDate;
//                    infobean.fExpDate = bean.endDate;
//                    infobean.fOrganization = bean.idOrg;
//                    infobean.fNationCode = bean.countryCode;
//                    infobean.fNation = bean.nation;
//                    infobean.fAddition = "";
//                    infobean.fingerData = new byte[0];
//                    
//                    //港澳居住证
//                    
//                    infobean.gFullName = bean.fullName;
//                    infobean.photoLocal = Environment.getExternalStorageDirectory() + "/"+"wltlib"+"/zp.bmp";
//                    infobean.gAddress = bean.idAddr;
//                    infobean.gGender = bean.sex;
//                    infobean.gCardTag = bean.cardType;
//                    infobean.gBirthday = bean.birthday;
//                    infobean.gIdentityCardNumber = bean.idNo;
//                    infobean.gEffectiveDate = bean.beginDate;
//                    infobean.gExpDate = bean.endDate;
//                    infobean.gOrganization = bean.idOrg;
//                    infobean.gPassNumber = bean.passportNo;
//                    infobean.gSignCount = bean.issuingNo;
//                    infobean.gReserveA = bean.reserveA;
//                    infobean.gReserveB = bean.reserveB;
//                    infobean.gReserveC = bean.reserveC;
//                    //Log.e("GJ", "infobean.photoLocal="+infobean.photoLocal);
//                    //Log.e("GJ", "infobean.gAddress="+infobean.photoLocal);
//                    String tmpType = type;
//                    if (type == null) {
//                        tmpType = "0";
//                    }
////Log.e("GJ", "bean.cardType="+bean.cardType);
//                    if (!bean.cardType.equals(tmpType)) {
//                        Bundle bundle2 = new Bundle();
//                        if ("0".equals(tmpType)) {
//                            bundle2.putString("code", "-1105");
//                            bundle2.putString("message", "实物证件与选择的证件类型不匹配，请放置二代居民身份证");
//                        } else if ("1".equals(tmpType)) {
//                            bundle2.putString("code", "-1106");
//                            bundle2.putString("message", "实物证件与选择的证件类型不匹配，请放置外国人永久居留证");
//                        }else if ("2".equals(tmpType)) {
//                            bundle2.putString("code", "-1107");
//                            bundle2.putString("message", "实物证件与选择的证件类型不匹配，请放置港澳台身份证");
//                        }
//
//                        if (callback != null) {
//                            callback.onFail(bundle2);
//                        }
//
//                    } else {
//                        if (callback != null) {
//                            bundle.putParcelable("data", infobean);
//                            callback.onSuccess(bundle);
//                        }
//
//                    }
//
//                }
//
//                @Override
//                public void onCompleted(Bundle bundle) {
//
//                }
//            },30000,true);
    	}
        
    }


    
    public void getFingerCode(final PeripheralCallback callback, int timeOut) {
    	TimeOut = timeOut;
        LogUtil.mLog("mediaPlayer  context ==" + mContext );
        if (mContext != null) {
            this.mediaPlayer = MediaPlayer.create(mContext, speakerId);
            LogUtil.mLog("mediaPlayer == " + mediaPlayer.toString());
//            try {
//                this.mediaPlayer.prepare();
//            } catch (IllegalStateException var3) {
//                var3.printStackTrace();
//            } catch (IOException var4) {
//                var4.printStackTrace();
//            }
        }
        
        if (this.mediaPlayer != null) {
            this.mediaPlayer.start();
            LogUtil.mLog("mediaPlayer start == " + mediaPlayer.toString());
        }

        
        if(CONNECTIONMODE == BTCONNECT){

    		//Log.e("GJjiaohang", "开始读取指纹中... 超时时间="+timeOut);
            TaskCallback taskCallback = new TaskCallback() {
                public void onStart(Bundle bundle) {
                }

                public void onSucceed(Bundle bundle) {
                    String fingerCode = bundle.getString("data");
                    Log.e("fingerPrint:", fingerCode);
                    byte[] data = Base64.decode(fingerCode, Base64.NO_WRAP);
                    if (callback != null) {
                        bundle.putByteArray("data", data);
                        bundle.putString("dataStr",fingerCode);
                        callback.onSuccess(bundle);
                    }

                }

                public void onError(Bundle bundle) {
                    if (callback != null) {

                		//Log.e("GJjiaohang", "读取失败... 错误信息"+bundle.getString("message"));
                        bundle.putString("code", "-1302");
                        bundle.putString("message", bundle.getString("message"));
                        callback.onFail(bundle);
                    }

                }
            };
            SiecomDevice.ReadFinger(3, taskCallback, timeOut);
        }else{
//        	policemen();
//        	
//        	if(!fingerprintConnection){
//        		connBtnClick();
//        	}
//        	if(fingerprintConnection){
//                mClient.tcGetFeature(5000, new Callback() {
//
//                    @Override
//                    public void onSuccess(FingerResult result) {
////                        displayMessage("获取特征成功");
//                        byte[] feature = result.getTemplate();
//                        Logs.i("GJ", "特征长度：" + (feature == null ? 0 : feature.length));
//                        ToastUtils.showToast(mContext, "获取成功");
//                        String strInfo = android.util.Base64.encodeToString(feature, Base64.NO_WRAP);
//                        
////                        infoText.setText(strInfo);
////                        showFingerImg(result.getImgBytes());
//                        Bundle bundle = new Bundle();
//                        if (callback != null) { 
//                            bundle.putString("data", strInfo);
//                            callback.onSuccess(bundle);
//                        }
//    ////Log.e("GJ", "指纹特征码"+strInfo);
//                    }
//
//                    @Override
//                    public void onError(int errorCode) {
//                        ToastUtils.showToast(mContext, "获取特征失败：" + errorCode);
////                        displayMessage("获取特征失败", errorCode);
//                    }
//                });
//        	}else{
//        		Bundle bundle = new Bundle();
//        		bundle.putString("code", "-1");
//                if (callback != null) {
//                    callback.onFail(bundle);
//                }
//        	}
//        
        }

    }
    private  static Bitmap tesoByte2bitmap(byte[] byBuffer){

        if(byBuffer.length>4000){

            Bitmap bitmap = BitmapFactory.decodeByteArray(
                    byBuffer, 0, byBuffer.length);
            return bitmap;

        }
        int bmpWidth = 152;
        int bmpHeigh = 200;
        Bitmap bmpFingerprint = Bitmap.createBitmap(bmpWidth, bmpHeigh,
                Bitmap.Config.ARGB_8888);
        int iPos = 0;
        byte[] buf = new byte[bmpWidth * bmpHeigh * 4];
        for (int x = 0; x < bmpWidth; x++) {
            for (int y = 0; y < bmpHeigh; y++) {
                iPos = y * bmpWidth + x;

                byte[] t = new byte[4];
                int pos = iPos / 8;

                byte c = byBuffer[pos];
                if ((byte) ((c >> (8 - iPos % 8)) & 0x1) == 0x00) {
                    //grep = 0xff;
                    t[0] = (byte) 0xff;
                    t[1] = (byte) 0xff;
                    t[2] = (byte) 0xff;
                    t[3] = (byte) 0xff;
                } else {
                    //grep = 0x00;
                    t[0] = (byte) 0x00;
                    t[1] = (byte) 0x00;
                    t[2] = (byte) 0x00;
                    t[3] = (byte) 0xff;
                }

                System.arraycopy(t, 0, buf, iPos * 4, t.length);
                //bmpFingerprint.setPixel(x, bmpHeigh - y - 1, iColor);
            }
        }
        Log.e("fin", System.currentTimeMillis() + "---");
        ByteBuffer buffer = ByteBuffer.wrap(buf);
        bmpFingerprint.copyPixelsFromBuffer(buffer);
        return  bmpFingerprint;

    }
    
    public void captureFingerCode(PeripheralCallback callback, int timeOut) {
    	TimeOut = timeOut;
        this.getFingerCode(callback, timeOut);
    }

    public void ReadIcCardTags(int ICtype, EmvOptions options, final PeripheralCallback callback, int timeOut) {
    	TimeOut = timeOut;
        Log.e("ReadIcCardTags", "ReadIcCardTags");
//        byte ICtype;
        if (ICtype == 2) {
            ICtype = 0;
        } else if (ICtype == 3) {
            ICtype = 1;
        } else {
            ICtype = 3;
        }

        TaskCallback taskCallback = new TaskCallback() {
            public void onStart(Bundle bundle) {
                SiecomPeripheral.this.now = System.currentTimeMillis();
                Log.e("ReadIcCardTags", "onStart");
            }

            public void onSucceed(Bundle bundle) {
                BankCardBean bean = (BankCardBean)bundle.getParcelable("data");
                long finish = System.currentTimeMillis();
                Log.e("useTime:", finish - SiecomPeripheral.this.now + "ms");
                byte type = 0;

                try {
                    if (bean.cardType == 0) {
                        type = 2;
                    } else if (bean.cardType == 1) {
                        type = 3;
                    }

                    BankCardInfoBean infobean = new BankCardInfoBean();
                    if (bean.cardType == 0) {
                        infobean.readMode = 2;
                    } else if (bean.cardType == 1) {
                        infobean.readMode = 3;
                    } else if (bean.cardType == 2) {
                        infobean.readMode = 1;
                    }

                    if (bean.cardType != 0 && bean.cardType != 1) {
                        infobean.cardNo = bean.cardNo;
                        infobean.track1Data = bean.oneMagneticTrack;
                        infobean.track2Data = bean.twoMagneticTrack;
                        infobean.track3Data = bean.threeMagneticTrack;
                    } else {
                        Log.e("info:", bean.ICChipData);
                        String userName = StringUtil.tagParse("5F20", bean.ICChipData);
                        byte[] nameByte = ByteTool.hexStr2Bytes(userName);

                        try {
                            infobean.userName = (new String(nameByte, "gb2312")).trim();
                            Log.e("userName：", (new String(nameByte, "gb2312")).trim());
                        } catch (UnsupportedEncodingException var20) {
                            var20.printStackTrace();
                        }

                        infobean.cardNo = bean.cardNo;
                        String credentialType = StringUtil.tagParse("9F62", bean.ICChipData);
                        infobean.credentialType = credentialType;
                        Log.e("credentialType：", credentialType);
                        String documentNumber = StringUtil.tagParse("9F61", bean.ICChipData);
                        byte[] documentByte = ByteTool.hexStr2Bytes(documentNumber);
                        infobean.documentNumber = (new String(documentByte)).trim();
                        Log.e("documentNumber：", (new String(documentByte)).trim());
                        int len5A = StringUtil.getTagLen(0, "5A", bean.ICChipData);
                        String track2Data = StringUtil.tagParse(len5A * 2 + 2, "57", bean.ICChipData);
                        track2Data = track2Data.replace("D", "=");
                        if (track2Data.indexOf("F") != -1) {
                            track2Data = track2Data.substring(0, track2Data.indexOf("F"));
                        }

                        infobean.track2Data = track2Data;
                        Log.e("track2Data：", track2Data);
                        String track1Data = StringUtil.tagParse("9F1F", bean.ICChipData);
                        infobean.track1Data = track1Data;
                        Log.e("track1Data：", track1Data);
                        String accountBalance = StringUtil.tagParse("9F79", bean.ICChipData);
                        infobean.accountBalance = accountBalance;
                        Log.e("accountBalance：", accountBalance);
                        String balanceCap = StringUtil.tagParse("9F77", bean.ICChipData);
                        infobean.balanceCap = balanceCap;
                        Log.e("balanceCap：", balanceCap);
                        String expDate = StringUtil.tagParse("5F24", bean.ICChipData);
                        //获取失效日期
                        if(expDate.equals("00000000") || TextUtils.isEmpty(expDate)){
                            expDate = getExpDataByTrack2(track2Data);
                        }
                        infobean.expDate = expDate;
                        Log.e("expDate：", expDate);
                        String serialNumber = StringUtil.tagParse("5F34", bean.ICChipData);
                        infobean.serialNumber = serialNumber;
                        Log.e("serialNumber：", serialNumber);
                        int pos = bean.ICChipData.indexOf("9F26");
                        if(pos != -1){
                            bundle.putString("55field", bean.ICChipData.substring(pos));
                        }else{
                            bundle.putString("55field", "");
                        }
                    }

                    if (callback != null) {
                        bundle.putInt("cardType", type);
                        bundle.putString("data", bean.ICChipData);
                        bundle.putParcelable("BankCardInfoBean", infobean);
                        callback.onSuccess(bundle);
                    }
                } catch (ArrayIndexOutOfBoundsException var21) {
                    var21.printStackTrace();
                    if (callback != null) {
                        bundle.putString("code", String.valueOf(var21.hashCode()));
                        bundle.putString("message", var21.getMessage());
                        callback.onFail(bundle);
                    }
                }

            }

            public void onError(Bundle bundle) {
                if (callback != null) {
                    bundle.putString("code", "-1708");
                    bundle.putString("message","获取55域数据超时");
                    callback.onFail(bundle);
                }

            }
        };
        options.setSupportPSESel((byte)1);
        byte[] Capability = new byte[]{-32, 96, -56};
        options.setCapability(Capability);
        byte[] ExCapability = new byte[]{96, 0, -16, 32, 1};
        options.setExCapability(ExCapability);
        options.setTransCurrExp((byte)2);
        options.setECTSI((byte)1);
        options.setEC_TermLimit(10000000);
        options.setEC_bTermLimitCheck((byte)1);
        byte[] TermTransQuali = new byte[]{36, 0, 0, -128};
        options.setTermTransQuali(TermTransQuali);
        options.setCL_bStatusCheck((byte)0);
        options.setCL_CVMLimit(10000000);
        options.setCL_FloorLimit(0);
        options.setCL_TransLimit(10000000);
        options.setTransNo(1);
        SiecomDevice.ReadBankCard(ICtype, options, taskCallback, timeOut);
    }

    /**
     * 
     */
    public void initEPP(){
//        int ret = m_sEPP.EPP_OpenDevice(PORT, 9600);
//        if(ret < 0){
//            portIsOpen = false;
//            Log.e(TAG, "打开串口失败");
//            ToastUtils.showToast(mContext, "打开串口失败");
//        }
//        else{
//            portIsOpen = true;
//            Log.e(TAG, "打开串口成功");
//            ToastUtils.showToast(mContext, "打开串口成功");
//        }
    }
    
    public static byte[] sm2PubKey;
    public static byte[] sm2PriKey;
    
    public void getPublicKey(final PeripheralCallback callback, int cipherTpye, int timeOut) {
    	TimeOut = timeOut;
    	if(CONNECTIONMODE == BTCONNECT){
    		TaskCallback taskCallback = new TaskCallback() {
	            public void onSucceed(Bundle bundle) {
	                callback.onSuccess(bundle);
	            }
	
	            public void onStart(Bundle bundle) {
	            }
	
	            public void onError(Bundle bundle) {
	                callback.onFail(bundle);
	            }
    		};
    		SiecomDevice.getPublicKey(taskCallback, cipherTpye, timeOut);
    		
    	}else{ // 一体机分支
    		Bundle bundle = new Bundle();
        	// 11国际算法 RSA  存储在索引1位置      12国密算法 SM2 存储至1位置
//        	if(cipherTpye == 11){
//        		byte[] rsaPub = new byte[128];
//    			byte[] rsaPri = new byte[128];
//    			int ret =0;
//    			String rsaPubStr = "";
//    			ret= m_sEPP.EPP_GenRsa1024(rsaPub,rsaPri);
//    			if(ret != 0)
//    			{
//    				DbgLogger.mLog("下载RSA pub密钥失败  ret=="+ret  );
//    				bundle.putString("code", ErrorDefine.ERR_GET_PUBLIC_KEY_FAIL + "");
//                	bundle.putString("message", "公钥获取失败");
//                	callback.onFail(bundle);
//    				DbgLogger.mLog("生成RSA密钥对失败");
//    				return;
//    			}
//    			
//    			rsaPubStr = ByteTool.byte2hex(rsaPub);
//    			DbgLogger.mLog("RSA公钥="+rsaPubStr+ "----RSA私钥=" + ByteTool.byte2hex(rsaPri));
//    			bundle.putString("data",rsaPubStr);
//    			callback.onSuccess(bundle);    			
//    			
//        	}
        	
        	//国密类型
//        	if(cipherTpye == 12){
//        		byte[] pSm2Pub = new byte[64];
//        		byte[] pSm2Pri = new byte[32];
//        		int ret = m_sEPP.EPP_GenSm2KeyPair(pSm2Pub, pSm2Pri);
//        		if(ret == 0){ //成功   
//        			sm2PriKey = pSm2Pri;
//        			sm2PubKey = pSm2Pub;
//        			String sm2PubStr = StringUtil.bytesToHexString(pSm2Pub, pSm2Pub.length);
//        			String sm2PriStr = StringUtil.bytesToHexString(pSm2Pri,pSm2Pri.length);
//        			DbgLogger.mLog("SM2公钥==" + sm2PubStr  + "----私钥==" + sm2PriStr);
////        			pSm2Pri = ByteTool.str2Bcd("5a0310d98677b07cfd92602d8bddc1a387edcb799bbd89c15d932583e2ea725d");
////        			pSm2Pub = ByteTool.str2Bcd("eb2e57575aba7d0167d42debe22c40410a0a7912079da06a4c661007a163db915271d6ef1b5f86eaa36f96ad39cae600c0011183abaebb6bcf6e4c4dc386616c");
//        			ret= m_sEPP.EPP_LoadSm2Pub(pSm2Pub);
//    				if(ret != 0){ 
//    					DbgLogger.mLog("下载sm2 pub密钥失败  ret=="+ret  );
//    					bundle.putString("code", ErrorDefine.ERR_GET_PUBLIC_KEY_FAIL + "");
//    	            	bundle.putString("message", "公钥获取失败");
//    	            	callback.onFail(bundle);
//    					return;
//    				}
//    				
//    				ret = m_sEPP.EPP_LoadSm2Pri(pSm2Pri);
//    				if(ret != 0){ 
//    					DbgLogger.mLog("下载sm2 pri密钥失败  ret=="+ret  );
//    					bundle.putString("code", ErrorDefine.ERR_GET_PUBLIC_KEY_FAIL + "");
//    	            	bundle.putString("message", "公钥获取失败");
//    	            	callback.onFail(bundle);
//    					return;
//    				}
//    				
//        			bundle.putString("data",sm2PubStr);
//        			callback.onSuccess(bundle);
//        		}else{ //失败
//        			bundle.putString("code", ErrorDefine.ERR_GET_PUBLIC_KEY_FAIL + "");
//                	bundle.putString("message", "公钥获取失败");
//                	callback.onFail(bundle);
//        		}
//        	}
    	}
        
    }

    /**
     *  cipherTpye   1.国际    2.国密
     */
    public void loadMainKey(final PeripheralCallback callback, byte[] content, int mainKeyCode, int cipherTpye, int timeOut) {
    	TimeOut = timeOut;
    	if(CONNECTIONMODE == BTCONNECT){  //蓝牙模式
    		TaskCallback taskCallback = new TaskCallback() {
	            public void onStart(Bundle bundle) {
	            }
	
	            public void onSucceed(Bundle bundle) {
	                callback.onSuccess(bundle);
	            }
	
	            public void onError(Bundle bundle) {
	                callback.onFail(bundle);
	            }
    		};
    		SiecomDevice.rsaCipherMainKey(taskCallback, content, indexKeyFix(mainKeyCode), cipherTpye, timeOut);
    	}else{ //一体机模式
    		Bundle bundle = new Bundle();
//        	if(cipherTpye == 1){//国际
//    			byte[] pPlainResult = new byte[128];
//    			byte[] EncDatabyte = content;
//    			DbgLogger.mLog("RSA解密密文："+ByteTool.byte2hex(EncDatabyte));
//    			//私钥解密主密钥
//    			int ret = m_sEPP.EPP_Rsa1024Dec(EncDatabyte, pPlainResult);
//    			String mainKeyStr = "";
//    			if(ret != 0){
//    				DbgLogger.mLog("RSA解密失败");
//    				bundle.putString("code", ErrorDefine.ERR_LOAD_MAIN_KEY_FAIL + "");
//                	bundle.putString("message", "未找到国密加密模式下的私钥");
//                	callback.onFail(bundle);
//    				return;
//    			}
//    			mainKeyStr = ByteTool.byte2hex(pPlainResult);
//    			DbgLogger.mLog("RSA解密成功："+mainKeyStr);
//    			
//    			
//    			//设置算法 国际
//    			ret = m_sEPP.EPP_SetAlgo((byte)0x01);  // 1 3des   2 sm4
//                if(ret == 0){
//              	  	DbgLogger.mLog("设置算法 "+ cipherTpye +"成功");
//                }else{
//              	  	DbgLogger.mLog("设置算法"+ cipherTpye +"失败");
//                }
//                mainKeyStr = mainKeyStr.substring(mainKeyStr.length()-32, mainKeyStr.length());
//                DbgLogger.mLog("截取后的主密钥=="+ mainKeyStr);
////                mainKeyStr = "31323334353637383132333435363738";
//                DbgLogger.mLog("最后的主密钥=="+ mainKeyStr);
//                //下载主密钥
//                byte[] KVC = new byte[32];
//                byte KeyID = (byte) mainKeyCode;
//                byte DecryptKeyId = (byte)0xFF; //明文下载 
//                content = ByteTool.str2Bcd(mainKeyStr);
//                byte keyLen = (byte)content.length;
//                ret = m_sEPP.EPP_LoadMasterKey(KeyID, DecryptKeyId,keyLen, content, KVC);
//                if(ret < 0){   //加载主密钥失败
//                	bundle.putString("code", ErrorDefine.ERR_LOAD_MAIN_KEY_FAIL + "");
//                	bundle.putString("message", "主密钥下载异常");
//                	callback.onFail(bundle);
//                }else{    //加载主密钥成功
//                	bundle.putByteArray("checkValue", KVC);  //校验值
//                	bundle.putString("data", ByteTool.byte2hex(KVC));
//                	DbgLogger.mLog("ByteTool.byte2hex==" + ByteTool.byte2hex(KVC));
//                	callback.onSuccess(bundle);
//                }
//    			
//        	}
        	
//        	if(cipherTpye == 2){//国密   先解密 再把解密结果放到主密钥索引1位置
//        		int ret;
//        		
////        		DbgLogger.mLog("content.length==" + content.length);
////        		DbgLogger.mLog("content==" + ByteTool.byte2hex(content));
////        		String data = "4B1629F3C8B59C0368FA66DFFB21502DB67350FE7EA6DFC4746E09208CB140B56473565910829AC4D12EDD26E1E0BAF76FF8180D3E3A91EBCF962F4FC2EE94B759FD14C89332D74019764AC06AEE659776BEA59D9CAE47E2D979FB7D792DC7E28D31F36D2CF1DEA467970D68777F07C8";
////        		content = ByteTool.str2Bcd(data);
//        		DbgLogger.mLog("content==" + ByteTool.byte2hex(content));
//        		byte[] pDataResult = new byte[content.length - 64 -32]; //
//        		DbgLogger.mLog("content.length==" + content.length);
//        		ret = m_sEPP.EPP_Sm2Dec(content.length, content, pDataResult);
//        		if(ret != 0){
//        			bundle.putString("code", ErrorDefine.ERR_LOAD_MAIN_KEY_FAIL + "");
//                	bundle.putString("message", "未找到国密加密模式下的私钥");
//        			return;
//        		}
//        		
//        		ret = m_sEPP.EPP_SetAlgo((byte)0x02);  // 1 3des   2 sm4
//                DbgLogger.mLog("设置算法ret=" + ret);
//                if(ret == 0){
//              	  DbgLogger.mLog("设置算法 "+ cipherTpye +"成功");
//                }else{
//              	  DbgLogger.mLog("设置算法"+ cipherTpye +"失败");
//                }
//        		
//        		byte[] KVC = new byte[32];
//                byte KeyID = 1;
//                byte DecryptKeyId = (byte)0xFF; //明文下载 
//                DbgLogger.mLog("解密后的数据是：" +ByteTool.bytearrayToHexString(pDataResult, pDataResult.length));
//                byte[] MKbyte = pDataResult;
////    			String str = "11111111111111111111111111111111";
////    			MKbyte = ByteTool.str2Bcd(str);
//    			DbgLogger.mLog("加载的主密钥数据是：" + ByteTool.byte2hex(MKbyte));
//                byte KeyLen = (byte)MKbyte.length;
//                ret = m_sEPP.EPP_LoadMasterKey(KeyID, DecryptKeyId,KeyLen, MKbyte, KVC);
//                if(ret < 0){   //加载主密钥失败
//                	bundle.putString("code", ErrorDefine.ERR_LOAD_MAIN_KEY_FAIL + "");
//                	bundle.putString("message", "主密钥下载异常");
//                	callback.onFail(bundle);
//                }else{    //加载主密钥成功
//                	bundle.putByteArray("checkValue", KVC);  //校验值
//                	bundle.putString("data", ByteTool.byte2hex(KVC));
//                	DbgLogger.mLog("主密钥校验值ByteTool.byte2hex==" + ByteTool.byte2hex(KVC));
//                	callback.onSuccess(bundle);
//                }
//        	}
    	}
    	
    	
    }

    /*
     * 
     * 如果只灌入国际秘钥没灌入国密 01
     * 如果只灌入国密未灌入国际 10
     * 如果全部灌入 11
     * 
     */
    public void loadWorkKey(final PeripheralCallback callback, byte[] content, int mainKeyCode, int workKeycode, int cipherTpye, int timeOut) {
    	TimeOut = timeOut;

    	String Sequence = SiecomDevice.SyncReadCodeName();
    	if(Sequence == null){
    	    Sequence =  "";
        }
    	if(Sequence.equals("01") && cipherTpye == 2){
    		SiecomDevice.SyncWriteCodeName("11");
    	}else if(Sequence.equals("10") && cipherTpye == 1){
    		SiecomDevice.SyncWriteCodeName("11");
    	}else if(!Sequence.equals("01") && !Sequence.equals("10") && !Sequence.equals("11")){
    		if(cipherTpye == 1)
    			SiecomDevice.SyncWriteCodeName("01");
    		else
    			SiecomDevice.SyncWriteCodeName("10");
    	}
    	
    	LogUtil.mLog("传入的工作密钥为：" + ByteTool.byte2hex(content));
    	if(CONNECTIONMODE == BTCONNECT){  //蓝牙模式
    		int keyindex = indexKeyFix(workKeycode);
            int mainKeyIndex = indexKeyFix(mainKeyCode);
            if (cipherTpye == 1) {
                keyindex = keyindex;
                mainKeyIndex = mainKeyIndex;
            }

            if (cipherTpye == 2) {
                keyindex += 10;
                mainKeyIndex += 10;
            }

            TaskCallback taskCallback = new TaskCallback() {
                public void onStart(Bundle bundle) {
                }

                public void onSucceed(Bundle bundle) {
                    callback.onSuccess(bundle);
                }

                public void onError(Bundle bundle) {
                    callback.onFail(bundle);
                }
            };
            SiecomDevice.inputWorkKey(keyindex, mainKeyIndex, content, taskCallback);
    	
    	}else{
//    		Bundle bundle = new Bundle();
////        	if(cipherTpye == 1){//国际
////        	if(cipherTpye == 2){//国密
//        		int ret = -1;
//        		ret = m_sEPP.EPP_SetAlgo((byte)cipherTpye);  // 1 3des   2 sm4
//                DbgLogger.mLog("设置算法ret=" + ret);
//                if(ret == 0){
//              	  DbgLogger.mLog("设置算法 "+ cipherTpye +"成功");
//                }else{
//              	  DbgLogger.mLog("设置算法"+ cipherTpye +"失败");
//                }
//        		
//        		byte[] KVC = new byte[32];
//    			byte KeyID = (byte) mainKeyCode;
//    			byte DecryptKeyId = (byte) workKeycode;	
//    			byte[] wKbyte = content;
//    			DbgLogger.mLog("工作密钥是==" + ByteTool.byte2hex(wKbyte));
//    			byte KeyLen = (byte)wKbyte.length;
//    			//----激活密钥---------
//    			ret = m_sEPP.EPP_ActiveKey(KeyID, DecryptKeyId);
//    			if(ret != 0){
//    				DbgLogger.mLog("激活密钥失败" );
//    				return;
//    			}
//    			//----下载工作密钥----
//    			ret = m_sEPP.EPP_LoadWorkKey(KeyID, DecryptKeyId, KeyLen, wKbyte, KVC);
//    			if(ret < 0){   //加载主密钥失败
//                	bundle.putString("code", ErrorDefine.ERR_LOAD_WORK_KEY_FAIL + "");
//                	bundle.putString("message", "工作密钥下载异常");
//                	callback.onFail(bundle);
//                }else{    //加载主密钥成功
//                	bundle.putByteArray("checkValue", KVC);  //校验值
//                	bundle.putString("data", ByteTool.byte2hex(KVC));
//                	callback.onSuccess(bundle);
//                }
    		
    	}
    	        
    }
    
    private static final int PWDCancel = 2;
    private static final int PWDConfirm = 3;
    private static final int PWDTimeOut = 5;
    
    public static Handler mHandler = null;
    public String mSecretText = "";
    public String mPwdCheck = ""; //保存第一次输入的pinblock
    public int inputTimes = 0;
    public int mTimeOut = 20;
    /*
     * 启动加密 获取密码键盘输入
     * times 次数
     * 
     * cipherTpye 加密类型 1-国际   2-国密
	*/
    public void getPin(int inPutTimes,String bankCardNo,final PeripheralCallback callback, final int cipherTpye,int timeOut){
    	TimeOut=timeOut;
    	if(CONNECTIONMODE == BTCONNECT){
    		int keyindex = 0;
            if (cipherTpye == 1) {
                keyindex += 0;
            }

            if (cipherTpye == 2) {
                keyindex += 10;
            }

            byte maxLen = 6;
            boolean encryptType = false;
            this.overFlag = true;

    		//Log.e("GJjiaohang", "密码开始读取...超时时间="+timeOut);
            TaskCallback callback1 = new TaskCallback() {
                public void onStart(Bundle bundle) {
                }

                public void onSucceed(Bundle bundle) {
                    if (callback != null) {
                        Log.e(TAG, "option ==" + bundle.getInt("option"));
                        if (bundle.getInt("option") == -1201) {
                            bundle.putString("code", "-1201");
                            bundle.putString("message", "用户取消输入");
                            callback.onFail(bundle);
                            SiecomPeripheral.this.overFlag = false;
                        } else if (bundle.getInt("option") == 1) {
                            int num = bundle.getInt("keyNum");
                            StringBuffer buf = new StringBuffer();

                            for(int i = 0; i < num; ++i) {
                                buf.append("*");
                            }

                            bundle.putString("data", buf.toString());
                            callback.onSuccess(bundle);
                        } else if (bundle.getInt("option") == 0) {
                            byte[] pin = bundle.getByteArray("password");
                            bundle.putString("data", ByteTool.byte2hex(pin));
                            callback.onSuccess(bundle);
                            SiecomPeripheral.this.overFlag = false;
                        }
                    }

                }

                public void onError(Bundle bundle) {
                    if (callback != null && SiecomPeripheral.this.overFlag) {
                        callback.onFail(bundle);

                		//Log.e("GJjiaohang", "密码键盘读取失败...错误信息="+bundle.getString("message"));
                    }

                }
            };
            SiecomDevice.getPin(keyindex, bankCardNo, "12345.00", timeOut, inPutTimes, maxLen, (byte)0, callback1);
    	}else{ //一体机分支
//    		inputTimes = inPutTimes;
//        	mTimeOut = timeOut;
//        	if(bankCardNo != null && bankCardNo.length() > 0){ 
//        		bankCardNo = StringUtil.dealCardNo(bankCardNo);
//        		int ret = m_sEPP.EPP_LoadCardNumber(bankCardNo.getBytes());
//        		if(ret < 0){
//        			DbgLogger.mLog("卡号下载失败==" + bankCardNo);
//        		}else{
//        			DbgLogger.mLog("卡号下载成功==" + bankCardNo);
//        		}
//        	}
//        	if(null == mHandler){
//        		mHandler = new Handler(){
//        	        public void handleMessage(Message msg){
//        	        	Bundle bundle = new Bundle();
//        	            switch(msg.what){
//        	                case 1: //每次输入回调 加密模式返回n个*
//        	                	bundle.putInt("option", KeyBroadModule.OP_INPUTTING);
//        	                	bundle.putString("data", mSecretText); 
//                                callback.onSuccess(bundle);
//        	                    break;
//        	                case PWDCancel:
//        	                    //密码输入取消
//        	                	bundle.putInt("option", KeyBroadModule.OP_CANCEL);
//        	                	bundle.putString("code", ErrorDefine.ERR_PINPAD_INPUT_CANCEL + "");
//    	                    	bundle.putString("message", "用户取消输入");
//    	                    	callback.onSuccess(bundle);
//        	                    break;
//        	                case PWDTimeOut:
//        	                    //密码输入超时
//        	                	bundle.putString("code", ErrorDefine.ERR_PINPAD_INPUT_TIMEOUT + "");
//    	                    	bundle.putString("message", "密码输入超时");
//    	                    	callback.onFail(bundle);
//        	                    break;
//        	                case PWDConfirm:
//        	                    //密码输入确认完成  //获取pinBlock
//        	                    byte[] bPinblock = new byte[16];
//        	                    
//        	                    int ret = m_sEPP.EPP_GetPinBlock(bPinblock);
//        	                    if(ret > 0){
//        	                    	if(inputTimes == 2){  //两次输入
//        	                    		if(mPwdCheck.isEmpty()){  //第一次输入时  mPwdCheck 为空
//        	                    			mPwdCheck = ByteTool.byte2hex(bPinblock);
//        	                    			startGetPin(callback,mTimeOut,0x06);
//        	                    		}else{  //第二次输入
//        	                    			if(mPwdCheck.equalsIgnoreCase(ByteTool.byte2hex(bPinblock))){
//            	                    			//两次输入 完成
//            	                    			bundle.putInt("option", KeyBroadModule.OP_FINISH);
//            	                    			String pinBlockStr = ByteTool.byte2hex(bPinblock);
//            	                    			if(cipherTpye == 1){ //3DES
//            	                    				pinBlockStr = pinBlockStr.substring(0, 16);
//            	        	                    }
//            	                    			bundle.putString("data", pinBlockStr);
//            	                    			bundle.putByteArray("password", bPinblock);
//            	                    			callback.onSuccess(bundle);
//            	                    			mPwdCheck = ""; //清空保存的密码
//            	                    		}else{
//            	                    			bundle.putString("code", ErrorDefine.ERR_TWO_PASSWORD_NOT_SAME + "");
//            	    	                    	bundle.putString("message", "码输入不一致");
//            	    	                    	callback.onFail(bundle);
//            	                    		}
//        	                    			
//        	                    		}
//        	                    		
//        	                    	}else{  //一次输入
//    	                    			bundle.putInt("option", KeyBroadModule.OP_FINISH);
//    	                    			bundle.putString("data", ByteTool.byte2hex(bPinblock));
//    	                    			bundle.putByteArray("password", bPinblock);
//    	                    			callback.onSuccess(bundle);
//        	                    	}
//        	                    	
//        	                    }else{ //获取pinblock失败
//        	                    	bundle.putString("code", ErrorDefine.ERR_WORKKEY_ENCRYPT + "");
//        	                    	bundle.putString("message", "工作密钥加密异常");
//        	                    	callback.onFail(bundle);
//        	                    }
//        	                    break;
//
//        	                default:
//        	                    break;
//        	            }
//        	            super.handleMessage(msg);
//        	        }
//        	    };
//        	}
//        	
//        	startGetPin(callback,timeOut,0x06);
    	}
    	
    	
    }
    
    public void startGetPin(PeripheralCallback callback,int timeOut,int inputLength){
//    	mSecretText = "";
//    	Bundle bundle = new Bundle();
//        byte bAuto = 0x00;  //0-不自动结束    1-自动结束
//        byte bEnabledBeep = 0x01;
//        byte bMinlen = (byte) inputLength;
//        byte bMaxlen = (byte) inputLength;
//        byte Pinformat = 0x01;  //0x01  ANSI X9.8  0x02  IBM3624 0x03  ANSII码
//        
//        
//        if(m_sEPP.EPP_ActiveKey((byte)0x01,(byte)0x01) == 0){
//        	DbgLogger.mLog("密码键盘 EPP_ActiveKey 激活密钥 1-1 成功");
//        }else{
//        	bundle.putString("code", ErrorDefine.ERR_LOAD_WORK_KEY_FAIL + "");
//        	bundle.putString("message", "密钥下载异常");
//        	callback.onFail(bundle);
//        }
//        int ret = 0;
//        ret = m_sEPP.EPP_SetPara((byte)0x02,(byte)0xFF); //设置密码填充方式
//        if(ret != 0){
//        	DbgLogger.mLog("设置填充方式失败");
//        	return;
//        }
//        DbgLogger.mLog("设置填充方式OK");
//        ret = m_sEPP.EPP_GetPin(Pinformat, bMinlen, bMaxlen, bAuto, timeOut, bEnabledBeep);
//        if(ret < 0){
//        	bundle.putString("code", ErrorDefine.ERR_LOAD_WORK_KEY_FAIL + "");
//        	bundle.putString("message", "工作密钥下载异常");
//        	callback.onFail(bundle);
//            return;
//        }
//
//
//        Thread thread=new Thread(new Runnable()
//        {
//            @Override
//            public void run()
//            {
//                byte[] KeyValue = new byte[255];
//                int ret = -1;
//
//                // TODO Auto-generated method stub
//                while(true)
//                {
//                    ret = m_sEPP.EPP_GetKey(KeyValue);
//                    Log.i("Key Press","EPP_GetKey ==" + ret + "----keyvalue0=" + String.valueOf((int)KeyValue[0]));
//                    if(ret==-3)
//                    {
//                        Message message5 = new Message();
//                        message5.what=PWDTimeOut;
//                        mHandler.sendMessage(message5);
//                        return;
//
//                    }
//                    if(ret == 0)
//                    {
//                        Log.v("Key Press", String.valueOf((int)KeyValue[0]));
//                        if(KeyValue[0]==0x80)
//                        {
//                            Message message5 = new Message();
//                            message5.what = PWDCancel;
//                            mHandler.sendMessage(message5);
//                            return;
//
//                        }
//                        switch(KeyValue[0])
//                        {
//                            case 0x2A:	//密码
//                                Message message = new Message();
//                                message.what=1;
//                                mSecretText += (char)KeyValue[0];
//                                mHandler.sendMessage(message);
//                                break;
//                            case 0x1B:	//取消
//                                Message message2 = new Message();
//                                message2.what = PWDCancel;
//                                mHandler.sendMessage(message2);
//                                return;
//                            case 0x21:	//超时
//                                Message message6 = new Message();
//                                message6.what = PWDTimeOut;
//                                mHandler.sendMessage(message6);
//                                return;
//                            case 0x08:	//退格
//                                Message message4 = new Message();
//                                message4.what=1;
//                                mSecretText = "";  //退格 把前面输入清除完
//                                mHandler.sendMessage(message4);
//                                break;
//                            case 0x0d:	//确认
//                                Message message3 = new Message();
//                                message3.what = PWDConfirm;
//                                mHandler.sendMessage(message3);
//                                return;
//                            default:break;
//                        }
//                    }
//                }
//            }
//        });
//        thread.start();
    }

    public void getPinNew (final int inPutLength,int inPutTime,
    		String bankCardNo,final PeripheralCallback callback, final int cipherTpye,int workKeyCode,int isCipher,int timeOut){
    	TimeOut = timeOut;
    	
    	if(CONNECTIONMODE == BTCONNECT){ //蓝牙连接分支
    		int keyindex = indexKeyFix(workKeyCode);
            if (cipherTpye == 1) {
                keyindex += 0;
            }

            if (cipherTpye == 2) {
                keyindex += 10;
            }

            byte maxLen = (byte)inPutLength;
            byte encryptType = 0;
            if (isCipher == 1) {
                encryptType = 3;
            }

            TaskCallback callback1 = new TaskCallback() {
                public void onStart(Bundle bundle) {
                }

                public void onSucceed(Bundle bundle) {
                    if (callback != null) {
                        Log.e("onfail", "==" + bundle.getInt("option") + "----" + -1201);
                        if (bundle.getInt("option") == -1201) {
                            bundle.putString("code", "-1201");
                            bundle.putString("message", "用户取消输入");
                            callback.onFail(bundle);
                        } else if (bundle.getInt("option") == 1) {
                            int num = bundle.getInt("keyNum");
                            StringBuffer buf = new StringBuffer();

                            for(int i = 0; i < num; ++i) {
                                buf.append("*");
                            }

                            bundle.putString("data", buf.toString());
                            callback.onSuccess(bundle);
                        } else if (bundle.getInt("option") == 0) {
                            byte[] pin = bundle.getByteArray("password");
                            bundle.putString("data", ByteTool.byte2hex(pin));
                            callback.onSuccess(bundle);
                        }
                    }

                }

                public void onError(Bundle bundle) {
                    if (callback != null) {
                        callback.onFail(bundle);
                    }

                }
            };
            SiecomDevice.getPin(keyindex, bankCardNo, "", timeOut, inPutTime, maxLen, encryptType, callback1);
    	}else{ // 一体机分支
//    		inputTimes = inPutTime;
//        	mTimeOut = timeOut;
//        	if(null == mHandler){
//        		mHandler = new Handler(){
//        	        public void handleMessage(Message msg){
//        	        	Bundle bundle = new Bundle();
//        	            switch(msg.what){
//        	                case 1: //每次输入回调 加密模式返回n个*
//        	                	bundle.putInt("option", KeyBroadModule.OP_INPUTTING);
//        	                	bundle.putString("data", mSecretText); 
//                                callback.onSuccess(bundle);
//        	                    break;
//        	                case PWDCancel:
//        	                    //密码输入取消
//        	                	bundle.putInt("option", KeyBroadModule.OP_CANCEL);
//        	                	bundle.putString("code", ErrorDefine.ERR_PINPAD_INPUT_CANCEL + "");
//    	                    	bundle.putString("message", "用户取消输入");
//    	                    	callback.onSuccess(bundle);
//        	                    break;
//        	                case PWDTimeOut:
//        	                    //密码输入超时
//        	                	bundle.putString("code", ErrorDefine.ERR_PINPAD_INPUT_TIMEOUT + "");
//    	                    	bundle.putString("message", "密码输入超时");
//    	                    	callback.onFail(bundle);
//        	                    break;
//        	                case PWDConfirm:
//        	                    //密码输入确认完成  //获取pinBlock
//        	                    byte[] bPinblock = new byte[16];
//        	                    int ret = m_sEPP.EPP_GetPinBlock(bPinblock);
//        	                    if(ret > 0){
//        	                    	if(inputTimes == 2){  //两次输入
//        	                    		if(mPwdCheck.isEmpty()){  //第一次输入时  mPwdCheck 为空
//        	                    			mPwdCheck = ByteTool.byte2hex(bPinblock);
//        	                    			startGetPin(callback,mTimeOut,inPutLength);
//        	                    		}else{  //第二次输入
//        	                    			if(mPwdCheck.equalsIgnoreCase(ByteTool.byte2hex(bPinblock))){
//            	                    			//两次输入 完成
//            	                    			bundle.putInt("option", KeyBroadModule.OP_FINISH);
//            	                    			String pinBlockStr = ByteTool.byte2hex(bPinblock);
//            	                    			if(cipherTpye == 1){ //3DES
//            	                    				pinBlockStr = pinBlockStr.substring(0, 16);
//            	        	                    }
//            	                    			bundle.putString("data", pinBlockStr);
//            	                    			bundle.putByteArray("password", bPinblock);
//            	                    			callback.onSuccess(bundle);
//            	                    			mPwdCheck = ""; //清空保存的密码
//            	                    		}else{
//            	                    			bundle.putString("code", ErrorDefine.ERR_TWO_PASSWORD_NOT_SAME + "");
//            	    	                    	bundle.putString("message", "码输入不一致");
//            	    	                    	callback.onFail(bundle);
//            	                    		}
//        	                    			
//        	                    		}
//        	                    		
//        	                    	}else{  //一次输入
//    	                    			bundle.putInt("option", KeyBroadModule.OP_FINISH);
//    	                    			bundle.putString("data", ByteTool.byte2hex(bPinblock));
//    	                    			bundle.putByteArray("password", bPinblock);
//    	                    			callback.onSuccess(bundle);
//        	                    	}
//        	                    	
//        	                    }else{ //获取pinblock失败
//        	                    	bundle.putString("code", ErrorDefine.ERR_WORKKEY_ENCRYPT + "");
//        	                    	bundle.putString("message", "工作密钥加密异常");
//        	                    	callback.onFail(bundle);
//        	                    }
//        	                    break;
//
//        	                default:
//        	                    break;
//        	            }
//        	            super.handleMessage(msg);
//        	        }
//        	    };
//        	}
//        	
//        	startGetPin(callback,timeOut,inPutLength);
    	}
    	
    }
    
    
    public void setCodeName(final String serialNo, final PeripheralCallback callback, int timeOut) {
    	TimeOut = timeOut;
        (new Thread(new Runnable() {
            public void run() {
                int ret = SiecomDevice.SyncWriteCodeName(serialNo);
                if (ret == 0) {
                    callback.onSuccess(new Bundle());
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("code", "-0801");
                    bundle.putString("message", "设置蓝牙名称失败");
                    callback.onFail(bundle);
                }

            }
        })).start();
    }

    public void getSerialNo(final PeripheralCallback callback, int timeout) {
    	TimeOut = timeout;
        TaskCallback taskCallback = new TaskCallback() {
            public void onStart(Bundle bundle) {
            }

            public void onSucceed(Bundle bundle) {
                byte[] code = bundle.getByteArray("data");
                Log.e("code", ByteTool.byte2hex(code));
                CRC32 crc32 = new CRC32();
                crc32.reset();
                crc32.update(code);
                StringBuffer buf = new StringBuffer(String.valueOf(crc32.getValue()));

                while(buf.length() < 16) {
                    buf.append("0");
                }

                String tmp = "ZG" + buf.toString();
                bundle.putByteArray("data", tmp.getBytes());
                callback.onSuccess(bundle);
                //Log.e("GJ", "序列号已经读取出来"+tmp);
            }

            public void onError(Bundle bundle) {
                callback.onFail(bundle);
            }
        };
        SiecomDevice.getSeialNo(taskCallback, timeout);
    }

    public void cancelOperation() {
        SiecomDevice.jiaohang_CancelTask(true);
    }

    public void getCodeName(final PeripheralCallback callback) {
        (new Thread(new Runnable() {
            public void run() {
                String code = SiecomDevice.SyncReadCodeName();
                Bundle bundle;
                if (code != null) {
                    bundle = new Bundle();
                    bundle.putString("data", code);
                    callback.onSuccess(bundle);
                } else {
                    bundle = new Bundle();
                    bundle.putString("code", "-0901");
                    bundle.putString("message", "获取蓝牙名称失败");
                    callback.onFail(bundle);
                }

            }
        })).start();
    }

    public void printDataBitmap(Bitmap data, PeripheralCallback callback) {
    }

    public int validateARPC(final int ICtype, final String content, final String script, final int authflag, final PeripheralCallback callback, final int timeout) {
    	TimeOut = timeout;
        (new Thread(new Runnable() {
            public void run() {
                byte[] ScriptResult = new byte[512];
                byte[] TC = new byte[512];

                try {
                    String scriptTmp = script;
                    if (authflag == 1) {
                        scriptTmp = "";
                    }

                    byte t = 0;
                    if (ICtype == 2) {
                        t = 0;
                    } else if (ICtype == 3) {
                        t = 1;
                    }

                    int ret = SiecomDevice.SyncARPCExecuteScript(t, content, scriptTmp, ScriptResult, TC);
                    Log.e("ret", ret + "----");
                    Bundle bundle;
                    if (ret == 0) {
                        bundle = new Bundle();
                        int len = ByteTool.getBytesLength(ScriptResult);
                        String sr = new String(ByteTool.hexStr2Bytes(ByteTool.byte2hex(ScriptResult, 0, len, false)));
                        len = ByteTool.getBytesLength(TC);
                        String TCstr = new String(ByteTool.hexStr2Bytes(ByteTool.byte2hex(TC, 0, len, false)));
                        String tagDF31 = StringUtil.tagParse("DF31", sr);
                        Log.e("DF31", sr);
                        if (tagDF31 != null && !tagDF31.trim().equals("") && tagDF31.trim().length() > 0 && tagDF31.substring(0, 1).equals("1")) {
                            Bundle bundle2 = new Bundle();
                            bundle2.putString("code", ErrorDefine.ERR_IC_ARPC_SCRIPT_FAIL);
                            bundle2.putString("message", "脚本执行失败");
                            bundle2.putString("ScriptResult", sr);
                            bundle2.putString("TC", TCstr);
                            callback.onFail(bundle2);
                            return;
                        }

                        JSONObject json = new JSONObject();

                        try {
                            json.put("ScriptResult", sr);
                            json.put("TC", TCstr);
                        } catch (JSONException var16) {
                            var16.printStackTrace();
                        }

                        bundle.putString("data", json.toString());
                        callback.onSuccess(bundle);
                    } else {
                        bundle = new Bundle();
                        bundle.putString("code", "-1808");
                        bundle.putString("message", "执行脚本错误");
                        callback.onFail(bundle);
                    }
                } finally {
                    SiecomDevice.shutDownCard();
                }

            }
        })).start();
        return 0;
    }


    public void printDataString(final String data, final PeripheralCallback callback) {
        (new Thread(new Runnable() {
            public void run() {
                JSONObject objJson = null;

                try {
                    objJson = new JSONObject(data);
                } catch (JSONException var5) {
                    var5.printStackTrace();
                }

                try {
                    if (SiecomPeripheral.this.mPrinter.analysisJson(objJson)) {
                        callback.onSuccess(new Bundle());
                    } else {
                        Bundle bundle = new Bundle();
                        bundle.putString("code", "-1501");
                        bundle.putString("message", "连接打印机失败");
                        callback.onFail(bundle);
                    }
                } catch (JSONException var4) {
                    var4.printStackTrace();
                    Bundle bundlex = new Bundle();
                    bundlex.putString("code", "-1502");
                    bundlex.putString("message", "打印数据解析错误");
                    callback.onFail(bundlex);
                }

            }
        })).start();
    }

    public void extendMethod(String arg0, String arg1, String arg2, String arg3, String arg4, PeripheralCallback arg5, int arg6) {
    }

    public void extendMethod2(String arg0, String arg1, String arg2, String arg3, String arg4, PeripheralCallback arg5, int arg6) {
    }

    public void getSignaturePhoto(String arg0, String arg1, PeripheralCallback arg2, int arg3) {
    }

    public void readICLoadDetail(int ICtype, final PeripheralCallback callback, int timeOut) {
    	TimeOut = timeOut;
//        byte ICtype;
        if (ICtype == 2) {
            ICtype = 0;
        } else if (ICtype == 3) {
            ICtype = 1;
        } else {
            ICtype = 3;
        }

        TaskCallback taskCallback = new TaskCallback() {
            public void onStart(Bundle bundle) {
            }

            public void onSucceed(Bundle bundle) {
                byte[] bytes = bundle.getByteArray("data");
                List<TradeLogBean> list = ByteTool.parseLog(bytes);
                JSONObject json = new JSONObject();
                JSONArray array = new JSONArray();

                try {
                    int i = 0;

                    for(Iterator var8 = list.iterator(); var8.hasNext(); ++i) {
                        TradeLogBean bean = (TradeLogBean)var8.next();
                        Log.e("logbean:", bean.getMerchName());
                        JSONObject item = new JSONObject();
                        item.put("tradeNo", String.valueOf(i));
                        item.put("beforeAmount", bean.getAmount());
                        item.put("afterAmount", bean.getOtherAmount());
                        item.put("transCurrCode", bean.getTransCurrCode());
                        item.put("tradeDate", bean.getDate());
                        item.put("tradeTime", bean.getTime());
                        item.put("transType", bean.getTransType());
                        item.put("transNo", bean.getTransNo());
                        item.put("countryCode", bean.getCountryCode());
                        item.put("merchName", bean.getMerchName());
                        array.put(item);
                    }

                    json.put("ICLoadDetail", array);
                    Bundle bundle2 = new Bundle();
                    bundle2.putString("data", json.toString());
                    callback.onSuccess(bundle2);
                } catch (JSONException var10) {
                    var10.printStackTrace();
                }

            }

            public void onError(Bundle bundle) {
                if (callback != null) {
                    callback.onFail(bundle);
                }

            }
        };
        SiecomDevice.ReadCardLog(ICtype, 1, taskCallback, timeOut);
    }

    public void readICTradeDetail(int ICtype, final PeripheralCallback callback, int timeOut) {
    	TimeOut = timeOut;
//        byte ICtype;
        if (ICtype == 2) {
            ICtype = 0;
        } else if (ICtype == 3) {
            ICtype = 1;
        } else {
            ICtype = 3;
        }

        TaskCallback taskCallback = new TaskCallback() {
            public void onStart(Bundle bundle) {
            }

            public void onSucceed(Bundle bundle) {
                byte[] bytes = bundle.getByteArray("data");
                Log.e("bytes", bytes.length + "---");
                List<TradeLogBean> list = ByteTool.parseLog(bytes);
                Log.e("size", list.size() + "---");
                JSONObject json = new JSONObject();
                JSONArray array = new JSONArray();

                try {
                    int i = 0;

                    for(Iterator var8 = list.iterator(); var8.hasNext(); ++i) {
                        TradeLogBean bean = (TradeLogBean)var8.next();
                        Log.e("logbean:", bean.getMerchName());
                        JSONObject item = new JSONObject();
                        item.put("tradeNo", String.valueOf(i));
                        item.put("authorizedAmount", bean.getAmount());
                        item.put("otherAmount", bean.getOtherAmount());
                        item.put("transCurrCode", bean.getTransCurrCode());
                        item.put("tradeDate", bean.getDate());
                        item.put("tradeTime", bean.getTime());
                        item.put("transType", bean.getTransType());
                        item.put("transNo", bean.getTransNo());
                        item.put("countryCode", bean.getCountryCode());
                        item.put("merchName", bean.getMerchName());
                        array.put(item);
                    }

                    json.put("ICTradeDetail", array);
                    Bundle bundle2 = new Bundle();
                    bundle2.putString("data", json.toString());
                    callback.onSuccess(bundle2);
                } catch (JSONException var10) {
                    var10.printStackTrace();
                }

                SiecomDevice.shutDownCard();
            }

            public void onError(Bundle bundle) {
                if (callback != null) {
                    callback.onFail(bundle);
                }

                SiecomDevice.shutDownCard();
            }
        };
        SiecomDevice.ReadCardLog(ICtype, 0, taskCallback, timeOut);
    }
    

    public void updateBin(String uri) {

        DeviceInterface.updateFw(uri, new DeviceCallback() {
            @Override
            public void onStart() {
                if (mContext!=null) {
//                    spb.progressiveStart();
//                    Snackbar.make(rootView, "connect……", Snackbar.LENGTH_LONG)
//                            .setAction("Action", null).show();
                }
            }

            @Override
            public void onError(Bundle bundle) {
                if (mContext!=null) {

//                    Snackbar.make(rootView, "err_code:" + bundle.getInt("code") + "--" + "err_describe:" + bundle.getString("message"), Snackbar.LENGTH_LONG)
//                            .setAction("Action", null).show();
//                    spb.progressiveStop();
                }
            }

            @Override
            public void onSuccess(Bundle bundle) {
//                infoText.setText("progress:" + bundle.getInt("data") + "%");
            }

            @Override
            public void onCompleted(Bundle bundle) {
//                if (mContext!=null) {
//                    spb.progressiveStop();
//                    infoText.setText("update finish!");
//                    Snackbar.make(rootView, "update finish!", Snackbar.LENGTH_LONG)
//                            .setAction("Action", null).show();
//                }
            }
        }, true);

    }

    /**
     * ARPC校验，这个方法没有展示出来
     */
    public void arpcExecuteScript() {


        /**
         * 这里可以做ARPC校验，这里是数据是测试的数据，百分百失败的,这个方法是在读取完ic卡的信息后传输给服务器，由服务器返回数据再执行，为了避免回调过多不再使用回调方法
         *
         */
        new Thread(new Runnable() {
            @Override
            public void run() {

                // TODO Auto-generated method stub
                byte[] ScriptResult = new byte[1024];
                byte[] TC = new byte[1024];
                /**
                 * 这是同步接口,cardtype传入bean的，根据Qpboc标准，非接式不能写脚本
                 */
//                int ret = DeviceInterface.ARPCExecuteScript(cardType, arpc, script, ScriptResult, TC);
//
//
//
//                Log.e("ARPC", "ret:" + ret + ",ScriptResult==" + ByteTool.bytearrayToHexString(ScriptResult, 1024));
//
//                Message msg = new Message();
//                msg.what = ret;
//                handler.sendMessage(msg);


            }
        }).start();


    }

    public void readIcLog() {
        //读取非接交易记录是  DeviceInterface.readPicLog(),用法一样
        DeviceInterface.readIcLog(new DeviceCallback() {
            @Override
            public void onStart() {
//                if (rootView != null) {
//                    infoText.setText("");
//                    spb.setVisibility(View.VISIBLE);
//                    spb.progressiveStart();
//
//                }
//                Toast.makeText(getContext(), getResources().getText(R.string.please_input_card), Toast.LENGTH_LONG).show();

            }

            @Override
            public void onError(Bundle bundle) {
//                if (rootView != null) {

//                    spb.progressiveStop();
//                }

//                Toast.makeText(getContext(), "err_code:" + bundle.getInt("code") + "--" + "err_describe:" + bundle.getString("message"), Toast.LENGTH_LONG).show();

            }

            @Override
            public void onSuccess(Bundle bundle) {
//                if (rootView != null) {
//                    List<TradeLogBean> list = bundle.getParcelableArrayList("data");
//                    StringBuffer buf = new StringBuffer();
//                    buf.append(getResources().getText(R.string.log)+":\r\n");
//                    for (TradeLogBean bean : list) {
//                        Log.e("name", bean.getMerchName());
//                        buf.append(getResources().getText(R.string.tenants)+":" + bean.getMerchName() + getResources().getText(R.string.amount)+" :" + bean.getAmount() + getResources().getText(R.string.date)+" :" + bean.getDate() + " " + bean.getTime() + "\r\n");
//                    }
//                    infoText.setText(buf.toString());
//                    spb.progressiveStop();
//                }

            }

            @Override
            public void onCompleted(Bundle bundle) {
//                if (rootView != null) {
//                    spb.progressiveStop();
//                }
            }
        }, 15000, true);

    }



    private void showCardInfo(BankCardInfoBean bean) {
        StringBuffer buf = new StringBuffer();
        buf.append("card:");

        if (bean.cardType == 0) {
            buf.append("IC\r\n");
            buf.append(bean.getCardNo());
            buf.append("\r\n");
            if (bean.getICChipData() != null) {
                buf.append("TLV:"+bean.getICChipData());
            }
        } else if (bean.cardType == 1) {
            buf.append(bean.getCardNo());
            buf.append("\r\n");
            buf.append("1:" + bean.track1Data + "\r\n");
            buf.append("2:" + bean.track2Data + "\r\n");
            buf.append("3:" + bean.track3Data + "\r\n");

        } else if (bean.cardType == 2) {
            buf.append(bean.getCardNo());
            buf.append("\r\n");
            if (bean.getICChipData() != null) {
                buf.append("TLV:" + bean.getICChipData());
            }
        }
        //Log.e("GJ", "数据等于："+buf.toString());
//        infoText.setText(buf.toString());
//        spb.progressiveStop();

    }

    /**
     * 读取nfc
     */
    public void readPiccCard() {
        DeviceInterface.readPiccInfo(new DeviceCallback() {
            @Override
            public void onStart() {
//                infoText.setText("");
//                spb.setVisibility(View.VISIBLE);
//                spb.progressiveStart();
//                Snackbar.make(rootView, getResources().getText(R.string.please_nfc_card), Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
            }

            @Override
            public void onError(Bundle bundle) {

//                Snackbar.make(rootView, "err_code:" + bundle.getInt("code") + "--" + "err_describe:" + bundle.getString("message"), Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
//                spb.progressiveStop();
            }

            @Override
            public void onSuccess(Bundle bundle) {
                BankCardInfoBean bean = bundle.getParcelable("data");
                showCardInfo(bean);
                // arpcBtn.setVisibility(View.VISIBLE);
            }

            @Override
            public void onCompleted(Bundle bundle) {
//                spb.progressiveStop();

            }
        }, 15000, true);

    }

    /**
     * 读取ic卡信息
     */
    public void readIcCard() {
        DeviceInterface.readIcInfo(new DeviceCallback() {
            @Override
            public void onStart() {
//                infoText.setText("");
//                spb.setVisibility(View.VISIBLE);
//                spb.progressiveStart();
//                Snackbar.make(rootView, getResources().getText(R.string.please_input_card), Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
            }

            @Override
            public void onError(Bundle bundle) {
//                Snackbar.make(rootView, "err_code:" + bundle.getInt("code") + "--" + "err_describe:" + bundle.getString("message"), Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
//                spb.progressiveStop();
                /**
                 * 一般ARPC都在这里实现
                 */
                //arpcExecuteScript()

            }

            @Override
            public void onSuccess(Bundle bundle) {


                BankCardInfoBean bean = bundle.getParcelable("data");
                showCardInfo(bean);
                //  arpcBtn.setVisibility(View.VISIBLE);
//                cardType = bean.cardType;
            }

            @Override
            public void onCompleted(Bundle bundle) {

//                spb.progressiveStop();

            }
        }, 15000, true);

    }

    /**
     * 刷磁条卡
     */
    public void swipeCard() {
        DeviceInterface.readMsr(new DeviceCallback() {
            @Override
            public void onStart() {
//                infoText.setText("");
//                spb.setVisibility(View.VISIBLE);
//                spb.progressiveStart();
//                Snackbar.make(rootView, getResources().getText(R.string.please_swipe_card), Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
            }

            @Override
            public void onError(Bundle bundle) {
//                Snackbar.make(rootView, "err_code:" + bundle.getInt("code") + "--" + "err_describe:" + bundle.getString("message"), Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
//                spb.progressiveStop();
            }

            @Override
            public void onSuccess(Bundle bundle) {
                BankCardInfoBean bean = bundle.getParcelable("data");
                showCardInfo(bean);
//                spb.progressiveStop();

            }

            @Override
            public void onCompleted(Bundle bundle) {
//                spb.progressiveStop();

            }
        }, 15000, true);

    }


    /**
     * 金融板下电
     */
    public void powerOff() {
        DeviceInterface.closeFinancial();
        powerFlag = false;
    }

    /**
     * 金融板上电
     * 第二个参数是是否在主线程内回调，在主线程回调可以操作界面元素
     * 15秒内检测上电成功与否。
     */
    public void powerOn() {

        DeviceInterface.openFinancial(new DeviceCallback() {
            @Override
            public void onStart() {

//                spb.setVisibility(View.VISIBLE);
//                spb.progressiveStart();

            }

            @Override
            public void onError(Bundle bundle) {
                powerFlag = false;
//                Snackbar.make(rootView, "err_code:" + bundle.getInt("code") + "--" + "err_describe:" + bundle.getString("message"), Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
//                spb.progressiveStop();

            }

            @Override
            public void onSuccess(Bundle bundle) {

//                Snackbar.make(rootView, "success！", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
                powerFlag = true;
//                spb.progressiveStop();
                //可以取到版本号
                byte[] ver = bundle.getByteArray("data");
                //1.0.4版本以上是新板子
                if (Integer.valueOf(ByteTool.byte2hex(ver)) > 10003) {

                    ToastUtils.showToast(mContext, "新金融版上电成功");
                    

                } else {

                    ToastUtils.showToast(mContext, "旧金融版上电成功");

                }


            }

            @Override
            public void onCompleted(Bundle bundle) {

//                spb.progressiveStop();

            }

        }, true);

    }
    
   
    
    
/*
 *  如果只灌入国际秘钥没灌入国密 01
 *  如果只灌入国密未灌入国际 10
 *  如果全部灌入 11
 */
    
	@Override
	public void getKeyStatus(PeripheralCallback var1, String var2, int var3) {
		// TODO 自动生成的方法存根
        JSONObject json = new JSONObject();
        String Sequence = SiecomDevice.SyncReadCodeName();

    	//Log.e("GJjiaohang", "开始读取秘钥状态");
        try { 
        	
        	 if(Sequence == null){
        		 json.put("GuoJiKey", 0);
         		 json.put("GuoMiKey", 0);
         		 
        		 Bundle bundle2 = new Bundle();
                 bundle2.putString("data", json.toString());
                 var1.onSuccess(bundle2);
             	//Log.e("GJjiaohang", "成功读取出来11"+json.toString());
                 
                 return;
        	 }
        	 
        	if(Sequence.equals("01")){
        		json.put("GuoJiKey", 1);
        		json.put("GuoMiKey", 0);
        	}else if(Sequence.equals("10")){
        		json.put("GuoJiKey", 0);
        		json.put("GuoMiKey", 1);
        	}else if(Sequence.equals("11")){
        		json.put("GuoJiKey", 1);
        		json.put("GuoMiKey", 1);
        	}else{
        		json.put("GuoJiKey", 1);
        		json.put("GuoMiKey", 0);
        	}
            
            
            Bundle bundle2 = new Bundle();
            bundle2.putString("data", json.toString());

        	//Log.e("GJjiaohang", "成功读取出来"+json.toString());
            var1.onSuccess(bundle2);
        } catch (JSONException var10) {
        	Bundle bundle2 = new Bundle();
            bundle2.putString("data", "null");
            //Log.e("GJjiaohang", "秘钥状态读取失败");
            var1.onFail(bundle2);
            var10.printStackTrace();
        }
	}

	public String getVersion(){
		Api mApi = new Api();
		byte[] mget = new byte[16];
		mApi.Sys_GetVersion(mget);
		return ByteTool.byte2hex(mget);
		
	}

    /**
     *
     */
    private boolean isOldVersion(String Ver){
	    if(TextUtils.isEmpty(Ver) || Ver.length() < 6){
	        return true;
        }
        boolean isOldVer = false;
        int verFirst = Integer.parseInt(Ver.substring(0,2));
        if(verFirst == 1){
            int verSecond = Integer.parseInt(Ver.substring(2,4));
            if(verSecond < 5){
                isOldVer = true;
            }else
            if(verSecond == 5){
                int verThird = Integer.parseInt(Ver.substring(4,6));
                if(verThird < 8){
                    isOldVer = true;
                }
            }

        }else if(verFirst == 2){
            isOldVer = false;
        }else if(verFirst == 3){
            int verSecond = Integer.parseInt(Ver.substring(2,4));
            if(verSecond < 1){
                isOldVer = true;
            }else
            if(verSecond == 1){
                int verThird = Integer.parseInt(Ver.substring(4,6));
                if(verThird < 8){
                    isOldVer = true;
                }
            }
        }else {
            isOldVer = true;
        }
        Log.e(TAG,"isOlderVerson == " + isOldVer);
        return isOldVer;
    }
	@Override
	public void getInitInfo(final PeripheralCallback var1, int cipherTpye, int timeout) {
		// TODO 自动生成的方法存根
		String Ver = getVersion();
		Log.e("GJ","数据等于"+Ver.substring(0, 6)+"总数据："+Ver);
//		if(Ver != null && !Ver.trim().equals("") && Ver.trim().length() > 5 && Ver != "030108" && !Ver.substring(0, 6).equals("030108")){
//            Bundle bundlex = new Bundle();
//            bundlex.putString("code", "-3202");
//            bundlex.putString("message", "预置信息不存在，请升级外设固件。");
//            var1.onFail(bundlex);
//            return;
//		}

        if(isOldVersion(Ver)){
            Bundle bundlex = new Bundle();
            bundlex.putString("code", "-3202");
            bundlex.putString("message", "预置信息不存在，请升级外设固件。");
            var1.onFail(bundlex);
            return;
        }

        TaskCallback taskCallback = new TaskCallback() {
            public void onStart(Bundle bundle) {
            }

            public void onSucceed(Bundle bundle) {
                byte[] code = bundle.getByteArray("data");
                
//                //Log.e("GJ", "结果是："+new String(code));
                String data = ByteTool.byte2hex(code);
                JSONObject json = new JSONObject();
//                String Sequence = SiecomDevice.SyncReadCodeName();
                try {
                	String pkEpp = data.substring(0, 128);
                	String vndSignEpp = data.substring(128, 256);
                	String randEpp = data.substring(256, 272);
                	String idVnd = data.substring(272, 280);
                	String schemeVer = data.substring(280, 284);
                	//Log.e("GJ", "pkEpp="+pkEpp+"\n"+
//                			"vndSignEpp="+vndSignEpp+"\n"+
//                			"randEpp="+randEpp+"\n"+
//                			"idVnd="+idVnd+"\n"+
//                			"schemeVer="+schemeVer);

            		json.put("pkEpp", pkEpp);
            		json.put("vndSignEpp", vndSignEpp);
            		json.put("randEpp", new String(ByteTool.hexStr2Bytes(randEpp)));
            		json.put("idVnd", idVnd);
            		json.put("schemeVer", schemeVer);
            		
                    Bundle bundle2 = new Bundle();
                    bundle2.putString("data", json.toString());
                    var1.onSuccess(bundle2);
                } catch (JSONException var10) {
                    var10.printStackTrace();
                	var1.onFail(bundle);
                }
                
//                CRC32 crc32 = new CRC32();
//                crc32.reset();
//                crc32.update(code);
//                StringBuffer buf = new StringBuffer(String.valueOf(crc32.getValue()));
//
//                while(buf.length() < 16) {
//                    buf.append("0");
//                }
//
//                String tmp = "ZG" + buf.toString();
//                bundle.putByteArray("data", tmp.getBytes());
//                var1.onSuccess(bundle);
            }

            public void onError(Bundle bundle) {
            	var1.onFail(bundle);
            }
        };
        SiecomDevice.getInitInfo(taskCallback, timeout);
        
	}

	@Override
	public void loadMainKeyCN(final PeripheralCallback callback, byte[] var2, byte[] var3, byte[] var4, byte[] var5, int var6,
			int var7, int var8) {

		
        TaskCallback taskCallback = new TaskCallback() {
            public void onStart(Bundle bundle) {
            }

            public void onSucceed(Bundle bundle) {
                Bundle bundle2 = new Bundle();
        		try {
        			
                    byte[] code = bundle.getByteArray("data");
                    String data = ByteTool.byte2hex(code);          
                    if(data != null && !data.trim().equals("") && data.trim().length() > 15){
                        bundle2.putString("data", data.substring(0,16));
                    }else{
                    	bundle2.putString("data", data);
                    }
                    callback.onSuccess(bundle2);
                  
        		} catch (NumberFormatException e) {
        			// 失败跳过再读取
//        			continue;
        			bundle2.putString("code", "-3301");
        			bundle2.putString("message", "主密钥下载异常");
                	callback.onFail(bundle2);
        			
        		}
        	
            }

            public void onError(Bundle bundle) {
            	bundle.putString("code", "-3301");
            	bundle.putString("message", "主密钥下载异常");
            	callback.onFail(bundle);
            }
        };
        if(var7 == 2){
        	var7 = 10;
        }else{
        	var7 = 0;
        }
        SiecomDevice.loadMainKeyCN(taskCallback,var2, var3,  var4, var5, var7,
    			var6, var8);
        
		
	}
    
}
